package org.openkoala.koala.wizard;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.m2e.core.project.ProjectImportConfiguration;
import org.eclipse.m2e.core.ui.internal.wizards.MavenImportWizard;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.openkoala.koala.mojo.KoalaProjectCreate;
import org.openkoala.koala.widget.Project;

/**
 * 创建并导入项目（使用进度条）
 * @author xmfang
 *
 */
@SuppressWarnings("restriction")
class CreateImportProject implements IRunnableWithProgress {

	public static final int CUSTOM_PROJECT = 0;
	public static final int STRUTS2_SAMPLE_PROJECT = 1;
	
	private Display display;
	private Shell shell;
	
	private Project project;
	private int projectType;

	public CreateImportProject(Display display, Shell shell, Project project, int projectType) {
		this.display = display;
		this.shell = shell;
		this.project = project;
		this.projectType = projectType;
	}

	public void run(IProgressMonitor monitor)
			throws InvocationTargetException, InterruptedException {
		monitor.beginTask("Running create and import project operation!", 4);

		createProject();
		monitor.worked(2);
		
		importProject();
		monitor.worked(3);

//		//修改项目字符编码格式为UTF-8
//		try {
//			ResourcesPlugin.getWorkspace().getRoot().getProject(project.getAppName()).setDefaultCharset("UTF-8", null);
//		} catch (CoreException e) {
//			e.printStackTrace();
//		}
		monitor.worked(4);

		if (monitor.isCanceled()) {
			throw new InterruptedException("had been canceled!");
		}
		monitor.done();
	}

	private void createProject() {
		KoalaProjectCreate koalaProjectCreate = new KoalaProjectCreate();
		try {
			if (projectType == CUSTOM_PROJECT) {
				koalaProjectCreate.createProject(project);
			} else if (projectType == STRUTS2_SAMPLE_PROJECT) {
				koalaProjectCreate.createSSJProject(project);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void importProject() {
		display.syncExec(new Runnable() {
			public void run() {
				List<String> urls = new ArrayList<String>();
				urls.add(project.getPath() + "/" + project.getAppName());
				WizardDialog dialog = new WizardDialog(shell,
						new MavenImportWizard(new ProjectImportConfiguration(), urls));
				dialog.open();
			}
		});
	}
}
